package com.jiuyuan.config.filter;

import com.jiuyuan.entity.vo.RespBean;
import com.jiuyuan.entity.vo.RespBeanEnum;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @program: hrms
 * @description: 判断url所需角色
 * @author: Feng
 * @create: 2023-02-16 10:24
 **/
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : configAttributes) {
            //所需权限
            String needRole = configAttribute.getAttribute();
            //为登陆权限
            if("ROLE_LOGIN".equals(needRole)){
                //当前账号是否已登录
                if(authentication instanceof AnonymousAuthenticationToken)
                    throw new AccessDeniedException(RespBeanEnum.NOT_LOGIN.getMessage());
                return;
            }
            //获取用户权限并进行对比
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                String role = authority.getAuthority();
                if(needRole.equals(authority.getAuthority()))
                    return;
            }
        }
        throw new AccessDeniedException(RespBeanEnum.AUTHORITY_DENIED.getMessage());
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
